﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using Brc_DSB.GetWay.DataBase;
using Brc_DSB.GetWay.Middleware;
using Ocelot.Configuration;
using Ocelot.Requester.QoS;
using Ocelot.Responses;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.Logging;

namespace Brc_DSB.GetWay.Polly
{
    public class RetryFactory : IRetryFactory
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly IRetryRepository _retry;
        private readonly IOcelotLoggerFactory _logger;

        public RetryFactory(IServiceProvider serviceProvider, IRetryRepository retry, IOcelotLoggerFactory logger)
        {
            _serviceProvider = serviceProvider;
            _retry = retry;
            _logger = logger;
        }

        public Response<DelegatingHandler> Get(DownstreamReRoute request)
        {
            var handler =_serviceProvider.GetService<RetryDelegatingHandlerDelegate>();
            if (handler != null)
            {
                return new OkResponse<DelegatingHandler>(handler(request, _retry, _logger));
            }
            return new ErrorResponse<DelegatingHandler>(new UnableToFindQoSProviderError($"could not find RetryProvider for {request.DownstreamScheme}{request.DownstreamAddresses}{request.DownstreamPathTemplate}"));
        }
    }
}
